﻿namespace DepartmentSpecificStoreView
{
    using System.Data;

    using Microsoft.SharePoint;

    public class DepartmentViewReferences
    {
        #region Fields

        DataTable _DepartmentDataTable;

        #endregion Fields

        #region Properties

        public string AllFields
        {
            get;
            set;
        }

        public string DepartmentCode
        {
            get;
            set;
        }

        public SPListItemCollection DepartmentData
        {
            get;
            set;
        }

        public DataTable DepartmentDataTable
        {
            get
            {
                if ( _DepartmentDataTable == null )
                    _DepartmentDataTable = new DataTable( );
                return _DepartmentDataTable;
            }
            set
            {
                _DepartmentDataTable = value;
            }
        }

        public string DepartmentName
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        public void PopulateCurrentDataCollection( SPWeb storeWeb )
        {
            PopulateCurrentDataCollection( storeWeb, string.Empty, string.Empty, string.Empty );
        }

        public void PopulateCurrentDataCollection( SPWeb storeWeb, string fieldValue, string fieldName, string listToSort )
        {
            TargetFieldsDataCollectionBL target = new TargetFieldsDataCollectionBL( );
            SPQuery newData = new SPQuery( );
            SPList localDepartmentData = storeWeb.Lists[ DepartmentName ];
            if ( !listToSort.Equals( string.Empty ) && DepartmentName.Equals( listToSort ) )
                newData.Query = "<Where><Eq><FieldRef Name='" + fieldName.Replace( " ", "_x0020_" ) + "' /><Value Type='Text'>" + fieldValue + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
            else
                newData.Query = "<OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
            newData.ViewFields = AllFields;
            DepartmentData = localDepartmentData.GetItems( newData );
            DepartmentDataTable = DepartmentData.GetDataTable( );
            DepartmentCode = target.GetDepartmentAbbriviations( storeWeb, DepartmentName );
        }

        #endregion Methods
    }
}